from django.shortcuts import render
from django.http import HttpResponse
from .models import Book
from .models import Author
from datetime import datetime
import random

# Create your views here.
# hello
def hello(request):
    # 返回
    text = "<h1>This is Book's web page .</h1>"
    return HttpResponse(text)

def show_views(request):
    return HttpResponse("新闻")


def showbooks(request):
    # 获取书籍内容   ①获取所有书籍;  ②传递字符串?   --仅显示所有作者用户名?
    all_book = Book.objects.all()
    book_list = []
    for book in all_book:
        # print("书籍:",book)
        item = []
        item.append(book.bookname)
        item.append(book.price)
        item.append(book.publishtime)
        # 添加大列表
        book_list.append(item)
    # print("所有数据:",book_list)
    # 字符串
    texts = "<h1>书籍内容</h1>"+str(book_list)
    # return HttpResponse("书籍内容")
    return HttpResponse(texts)


def showauthors(request):
    authors = Author.objects.all()
    lists = []
    for element in authors:
        name = element.authorname
        lists.append(name)
    # print("作者列表:",lists)
    return HttpResponse("作者信息:"+str(lists))


def index(request):
    # return HttpResponse("INDEX")   # 显示文字
    # 显示html
    return render(request,"index.html")

def showcurrenttime(request):
    currenttime = datetime.now().today()
    # return HttpResponse("当前时间:"+str(currenttime))
    context = {"current":currenttime}
    return render(request,"index.html",context)

def shownumbers(request):
    number = random.randint(100,1000)
    context = {"nubmer":number}
    # return HttpResponse("显示")
    return render(request,"numbers.html",context)

def showdata(request):
    # 产生列表值
    lists = [90,45,23,11,199,100]
    return render(request,"data.html",{"data":lists})


def books(request):
    # 方式1
    # 获取书籍内容   ①获取所有书籍;  ②传递字符串?   --仅显示所有作者用户名?
    all_book = Book.objects.all()
    book_list = []
    for book in all_book:
        # print("书籍:",book)
        item = []
        item.append(book.bookname)
        item.append(book.price)
        item.append(book.publishtime)
        # 添加大列表
        book_list.append(item)
    return render(request,"books.html",{"booklist":book_list,"books":all_book})


def show_mybooks(request):
    # 所有数据传递
    bookdata = Book.objects.all()
    context = {"bookdata":bookdata}
    # 3个参数
    return render(request,"mybooks.html",context)


def detail(request,bookid):
    # 加载图书
    # book = Book.objects.get(id=1)
    book = Book.objects.get(id=bookid)
    # 获取图书信息
    # author = Author.objects.get(book=book)
    author = book.authorid
    return render(request,"detail.html",{"mybook":book,"myauthor":author})